package com.leap.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leap.entity.*;
import com.leap.entity.dto.CommentDTO;
import com.leap.entity.vo.CommentChildVO;
import com.leap.entity.vo.CommentVO;
import com.leap.entity.vo.CommentVOList;
import com.leap.mapper.CommentMapper;
import com.leap.service.AccountService;
import com.leap.service.CommentService;
import com.leap.utils.Const;
import com.leap.utils.JwtUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@RestController
@RequestMapping("/api/comment")
@Tag(name = "评论相关接口服务")
@Slf4j
public class CommentController {

    @Autowired
    JwtUtils utils;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    CommentService commentService;

    @Autowired
    AccountService accountService;


    /**
     * 评论集合获取
     * @param page
     * @param channelId
     * @return
     */
    @Operation(summary = "评论集合获取欧接口")
    @GetMapping("/list")
    public RestBean<CommentVOList> selectList(int page,int channelId,
                                          HttpServletRequest request) {
        Page<Comment> pageInfo = new Page<>(page, Const.PAGE_SIZE);
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);

        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Comment::getLikeCount);
        wrapper.orderByDesc(Comment::getCreateTime);
        wrapper.eq(Comment::getType, 0);

        if (channelId < 0 || channelId > 4 ){
            throw new StringIndexOutOfBoundsException("未知错误 请稍后重试！");
        }
        wrapper.eq(Comment::getChannelId, channelId);

        commentService.page(pageInfo, wrapper);

        List<Comment> commentList = pageInfo.getRecords();
        if (commentList.isEmpty()){
            throw new StringIndexOutOfBoundsException();
        }

        Long num = commentService.getSumByChannelId(channelId);

        List<Long> interactComments = accountService.loadCommentLikeList(accountId);

        List<CommentVO> list = commentList.stream().map(item -> {
            Long id = item.getAccountId();
            Account account = accountService.getById(id);

            Long commentId = item.getId();
            List<CommentChildVO> commentChildVOList = commentService.selectChildListById(commentId,interactComments);

            if (interactComments.size() > 0){
                return CommentVO.builder()
                        .id(item.getId())
                        .avatar(account.getAvatar())
                        .nickname(account.getName())
                        .content(item.getContent())
                        .subComments(commentChildVOList)
                        .likeCount(item.getLikeCount())
                        .isLiked(interactComments.contains(item.getId()) ? 1:0)
                        .showAllSubComments(0)
                        .createTime(item.getCreateTime())
                        .build();
            }else{
                return CommentVO.builder()
                        .id(item.getId())
                        .avatar(account.getAvatar())
                        .nickname(account.getName())
                        .content(item.getContent())
                        .subComments(commentChildVOList)
                        .likeCount(item.getLikeCount())
                        .isLiked(0)
                        .showAllSubComments(0)
                        .createTime(item.getCreateTime())
                        .build();
            }
        }).toList();

        CommentVOList commentVOList = CommentVOList.builder()
                .sum(num)
                .commentVOS(list)
                .build();

        return RestBean.success(commentVOList);
    }


    /**
     * 新增评论
     * @param commentDTO
     * @return
     */
    @Operation(summary = "评论发表接口")
    @PostMapping("/save")
    public RestBean<CommentVO> save(@RequestBody CommentDTO commentDTO,
                                    HttpServletRequest request) {
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);
        Comment comment = commentService.saveDTO(commentDTO,accountId);

        Account account = accountService.getById(accountId);

        CommentVO commentVO = CommentVO.builder()
                .id(comment.getId())
                .avatar(account.getAvatar())
                .nickname(account.getName())
                .content(comment.getContent())
                .channelId(comment.getChannelId())
                .subComments(List.of())
                .likeCount(comment.getLikeCount())
                .isLiked(0)
                .showAllSubComments(0)
                .createTime(comment.getCreateTime())
                .build();

        return RestBean.success(commentVO);
    }


    /**
     * 删除评论
     * @param id
     * @return
     */
    @Operation(summary = "评论删除接口")
    @DeleteMapping()
    public RestBean<String> delete(Long id) {

        commentService.deleteDTO(id);
        return RestBean.success("");
    }

    /**
     * 主评论查找
     * @param id
     * @return
     */
    @Operation(summary = "主评论查找接口")
    @GetMapping("/find")
    public RestBean<CommentVO> selectById(@RequestParam Long id,
                                          HttpServletRequest request) {
        String headerToken = request.getHeader("Authorization");
        Long accountId = utils.getAccountIdByToken(headerToken);

        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getId, id);

        Comment one = commentService.getOne(wrapper);

        Long onetId = one.getAccountId();
        Long commentId = one.getId();
        Account account = accountService.getById(onetId);

        List<Long> interactComments = accountService.loadCommentLikeList(accountId);

        List<CommentChildVO> commentChildVOList = commentService.selectChildListById(commentId,interactComments);

        CommentVO commentVO = null;
        if (!interactComments.isEmpty()){
            commentVO = CommentVO.builder()
                    .id(one.getId())
                    .avatar(account.getAvatar())
                    .nickname(account.getName())
                    .channelId(one.getChannelId())
                    .content(one.getContent())
                    .subComments(commentChildVOList)
                    .likeCount(one.getLikeCount())
                    .isLiked(interactComments.contains(one.getId()) ? 1:0)
                    .showAllSubComments(0)
                    .createTime(one.getCreateTime())
                    .build();
        }else{
            commentVO = CommentVO.builder()
                    .id(one.getId())
                    .avatar(account.getAvatar())
                    .channelId(one.getChannelId())
                    .nickname(account.getName())
                    .content(one.getContent())
                    .subComments(commentChildVOList)
                    .likeCount(one.getLikeCount())
                    .isLiked(0)
                    .showAllSubComments(0)
                    .createTime(one.getCreateTime())
                    .build();
        }

        return RestBean.success(commentVO);
    }

}


